<template>
    <el-form ref="form" label-width="80px" class="mainDiv">
                <el-form-item label="开单客户">
                    <div style="height:115px; display: flex">
                        <div style="display: flex;flex-direction: column">
                            <el-select v-model="ginfo.name" filterable remote placeholder="请输入关键词" :remote-method="searchguest" :loading="loading" @change="selectguest" default-first-option style="float: left;margin-right: 10px;" :disabled="issanke">
                                <el-option v-for="item in guestlist" :key="item.id" :label="item.name" :value="item.id" style="height: 68px">
                                    <div style="display: flex; flex-direction: column">
                                        <div>
                                            <span style="font-weight: 900;">{{item.name}}</span>
                                            <span style="float: right;font-size: 11px;color: #dc35af;">{{item.shopname}}</span>
                                        </div>
                                        <span style="font-size: 12px;margin-left: 10px;">{{item.phone}}</span>
                                    </div>
                                </el-option>
                            </el-select>
                            <div>
                                <el-switch @change="changesanke" v-model="issanke" style="margin: 0px 10px 0px 0px;" on-text="散" off-text="散" :width="45"></el-switch>
                                <el-radio v-model="ginfoid" :label="1" v-show="issanke">女</el-radio>
                                <el-radio v-model="ginfoid" :label="2" v-show="issanke">男</el-radio>
                            </div>
                            <el-button type="primary" icon="plus" size="small" @click="addRow(orderListRef)" style="width: 70px">加一行</el-button>
                        </div>
                        <div v-show="ginfo.id && !issanke">
                            <el-card :body-style="{ padding: '0px' }" shadow="hover">
                                <el-row style="display: flex;height:113px;align-items: center;">
                                    <img :src="ginfo.headurl" style="border-radius: 50%; width: 50px; height:50px;padding: 5px">
                                    <div style="padding: 0 10px">
                                        <p style="margin: 0px; height: 30px; line-height: 30px">
                                            <span @click="openGuestPage(ginfo.id)" style="cursor:pointer;color:#f50">{{ginfo.name}}</span>
                                            <span style="margin-left: 10px;font-size: 13px;color: #999;"><i class="iconfont el-icon-h-dianhua1"></i> {{ginfo.phone}}</span>
                                            <span style="margin-left: 10px;font-size: 13px;color: #999;"><i class="iconfont el-icon-h-yue01"></i> {{ginfo.balance}}</span>
                                            <span style="margin-left: 10px;font-size: 13px;color: #999;"><i class="iconfont el-icon-h-zengsong"></i> {{ginfo.giftbalance}}</span>
                                            <span style="font-size: 13px;color: #999;"><i class="iconfont el-icon-h-level"></i> {{ginfo.vipcard}}</span>
                                             产品折扣：
                                            <span style="font-size: 13px;color: #999;">{{ginfo.goodsdiscount}}</span>
                                             项目折扣：
                                            <span style="font-size: 13px;color: #999;">{{ginfo.subjectdiscount}}</span>
                                        </p>
                                        <el-input type="textarea" :rows="3" v-model="ginfo.remarks" class="textarea-remarks"></el-input>
                                    </div>
                                </el-row>
                            </el-card>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="消费内容" class="itemClass">
                    <el-table :data="orderlist" height="100%" show-summary :summary-method="sumorderlist" border :row-key="getrowid" :expand-row-keys="expands">
                        <el-table-column prop="userTypeList" label="" width="50" type="expand">
                            <template slot-scope="scope">
                                <div style="display: flex">
                                  <div style="display: flex;height: 34px;border: 1px solid #ebeef5;margin-right: 10px" v-for="(ite,ind) in scope.row.userTypeList">
                                    <span style="padding: 0 10px;text-align: center;font-weight: 700;color: rgb(144, 147, 153);">{{ite.name}}</span>
                                    <el-input class="table-line-input" size="small" style="border-left:1px solid rgb(235, 238, 245);width: 100px" :value="ite.username"  @blur="checkUserName($event, ite)" @focus="setIndex(scope.$index, 11 + ind * 2, orderListRef)" :ref="makeIndex(scope.$index, 11 + ind * 2, orderListRef)" @keyup.enter.native="searchUser($event, ite)">
                                      <i slot="suffix" class="el-icon-search" style="width: 25px;cursor: pointer;" @click="firstPopupUser(scope, ind, ite)"></i>
                                    </el-input>
                                    <el-input class="table-line-input" size="small" style="border-left: 1px solid rgb(235, 238, 245);width:60px" :value="ite.fuwutype|fuwuType" @blur="checkUserValue($event, ite.fuwutype)" @focus="setIndex(scope.$index, 12 + ind * 2, orderListRef)" :ref="makeIndex(scope.$index, 12 + ind * 2, orderListRef)" @keyup.enter.native="selectFuWuType($event, ite, fuwuType)"></el-input>
                                    <div style="border-left: 1px solid rgb(235, 238, 245);position: relative;">
                                        <el-popover placement="right" width="280">
                                            <div style="display: flex; flex-direction: column;width: 280px;height: 300px;">
                                              <div>
                                                <el-popover
                                                  placement="right-start"
                                                  title="选择员工"
                                                  width="200"
                                                  trigger="focus">
                                                  <el-table :data="userLists" max-height="300" style="cursor: pointer" @row-click="(row) => selectRow(row, ite)">
                                                    <el-table-column width="100" property="worknum" label="工号"></el-table-column>
                                                    <el-table-column width="100" property="name" label="姓名"></el-table-column>
                                                  </el-table>
                                                  <el-input slot="reference" @keyup.native="selUser($event)" class="table-line-input" size="small" placeholder="请按回车选择员工" style="border: 1px solid rgb(235, 238, 245);border-radius: 4px;"></el-input>
                                                </el-popover>
                                              </div>
                                              <div style="height: 100%;overflow: scroll;margin-top: 10px">
                                                <div style="display: flex;align-items: center;justify-content: space-between;line-height: 30px;margin-left: 5px;" v-for="(items, index) in ite.userFenList">
                                                    <span style="max-width: 125px;overflow: hidden;height: 30px">{{ items.worknum }} - {{ items.name }}</span>
                                                    <div>
                                                      <el-select v-model="items.fuwutype" placeholder="请选择" size="mini" style="width:70px;margin-right: 5px" @change="shuaxin" :disabled="items.disabled">
                                                        <el-option
                                                          v-for="item in fuwuType"
                                                          :key="item.value"
                                                          :label="item.name"
                                                          :value="item.value">
                                                        </el-option>
                                                      </el-select>
                                                      <input @keyup="changePercent(ite.userFenList, items)" style="width: 40px;height: 24px;outline: none;margin-right: 5px;border-radius: 3px;border: 1px solid #dcdfe6;text-align: center;"  v-model="items.percent" type="text" :disabled="items.disabled"/>
                                                      <i class="el-icon-circle-close-outline" style="cursor: pointer" v-if="items.disabled"></i>
                                                      <i class="el-icon-circle-close-outline" style="cursor: pointer" @click="deleteList(index, ite)" v-else></i>
                                                    </div>
                                                </div>
                                              </div>
                                            </div>
                                            <i slot="reference" class="el-icon-plus" style="line-height: 32px;cursor: pointer;color: rgb(144, 147, 153);font-size:13px;padding: 0 10px;"></i>
                                        </el-popover>
                                        <span style="position: absolute;top: -10px;right: -10px;background: red;color: #fff;border-radius: 50%;width: 20px;height: 20px;text-align: center;line-height: 20px;box-shadow: 0 0 11px 2px #cecece;" v-show="ite.userFenList && ite.userFenList.length > 1">{{(ite.userFenList && ite.userFenList.length)}}</span>
                                    </div>
                                  </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column type="index" width="40"></el-table-column>
                        <el-table-column prop="rowtype" label="类别" width="40">
                            <template slot-scope="scope">
                                <el-input class="table-line-input" :value="returnValue(scope, orderListRowType)" size="small" :ref="makeIndex(scope.$index, 1, orderListRef)" @focus="setIndex(scope.$index, 1, orderListRef)" @blur="checkValue($event, scope, orderListRowType)" @keyup.enter.native="selectValue($event, scope, orderListRowType, orderListRef)">
                                </el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="typename" label="品项名称" width="130" :show-overflow-tooltip="true">
                            <template slot-scope="scope">
                                <el-input class="table-line-input" :ref="makeIndex(scope.$index, 2, orderListRef)" @focus="setIndex(scope.$index, 2, orderListRef)" :value="scope.row.typename" size="small" @blur="blurcheck($event, scope.row.typename)" @keyup.enter.native="searchOpenOrderGoods($event, scope)">
                                    <i slot="suffix" class="el-icon-search" style="line-height: 32px;width: 25px;cursor: pointer;" @click="firstPopupType(scope)"></i>
                                </el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="type" label="消费类型" width="70">
                            <template slot-scope="scope">
                                <el-tag size="mini" type="success" v-if="scope.row.type == 1">产品</el-tag>
                                <el-tag size="mini" type="primary" v-else>项目</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="cardname" label="所属卡" width="130"></el-table-column>
                        <el-table-column prop="price" label="原价" width="60"></el-table-column>
                        <el-table-column prop="num" label="数量" width="50">
                            <template slot-scope="scope">
                                <span v-if="scope.row.consumetype == 2 && scope.row.cardtype == 1">{{scope.row.num}}</span>
                                <el-input class="table-line-input" :ref="makeIndex(scope.$index, 3, orderListRef)" @focus="setIndex(scope.$index, 3, orderListRef)" v-model="scope.row.num" size="small" v-else @keyup.native="getTotal(scope.row)" @keyup.enter.native="nextInput(orderListRef)">
                                </el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="nownum" label="可用" width="50">
                            <template slot-scope="scope">
                                <span v-if="scope.row.cardtype == 2 || scope.row.consumetype == 3">{{scope.row.nownum}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="discount" label="折扣" width="80">
                            <template slot-scope="scope">
                                <span v-if="scope.row.consumetype != 1">{{scope.row.discount}}</span>
                                <el-input class="table-line-input" v-else :ref="makeIndex(scope.$index, 4, orderListRef)" @focus="setIndex(scope.$index, 4, orderListRef)" v-model="scope.row.discount" size="small" @keyup.native="getTotal(scope.row)" @keyup.enter.native="nextInput(orderListRef)"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="amount" label="小计" width="80">
                            <template slot-scope="scope">
                                <el-input class="table-line-input" v-if="scope.row.consumetype == 1 || scope.row.cardtype == 1" :ref="makeIndex(scope.$index, 5, orderListRef)" @focus="setIndex(scope.$index, 5, orderListRef)" v-model="scope.row.amount" size="small" @change="getdiscount(scope.row)" @keyup.enter.native="nextInput(orderListRef)"></el-input>
                                <span v-else>{{scope.row.amount}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="usemoney" label="现金" width="80">
                            <template slot-scope="scope">
                                <el-input :ref="makeIndex(scope.$index, 6, orderListRef)" v-if="scope.row.consumetype == 1 || scope.row.cardtype == 1" @focus="setIndex(scope.$index, 6, orderListRef)" @keyup.enter.native="nextInput(orderListRef)" class="money table-line-input" placeholder="元" v-model="scope.row.usemoney" size="small"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="usebalance" label="余额" width="80">
                            <template slot-scope="scope">
                                <el-input :ref="makeIndex(scope.$index, 7, orderListRef)" v-if="scope.row.consumetype == 1 || scope.row.cardtype == 1" @focus="setIndex(scope.$index, 7, orderListRef)" @keyup.enter.native="nextInput(orderListRef)" class="money table-line-input" placeholder="元" v-model="scope.row.usebalance" size="small" :disabled="issanke"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="usegiftbalance" label="赠送余额" width="80">
                            <template slot-scope="scope">
                                <el-input :ref="makeIndex(scope.$index, 8, orderListRef)" v-if="scope.row.consumetype == 1 || scope.row.cardtype == 1" @focus="setIndex(scope.$index, 8, orderListRef)" @keyup.enter.native="nextInput(orderListRef)" class="money table-line-input" placeholder="元" v-model="scope.row.usegiftbalance" size="small" :disabled="issanke"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="usecard" label="卡付" width="80">
                        </el-table-column>
                        <el-table-column prop="isgift" label="赠" width="50">
                            <template slot-scope="scope">
                                <el-input class="table-line-input" v-if="scope.row.consumetype == 1" :ref="makeIndex(scope.$index, 9, orderListRef)" @focus="setIndex(scope.$index, 9, orderListRef)" :value="returnValue(scope, trueOrFalse)" @blur="checkValue($event, scope, trueOrFalse)" size="small" @keyup.enter.native="selectValue($event, scope, trueOrFalse, orderListRef)"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="istemp" label="存" width="50">
                            <template slot-scope="scope">
                                <el-input class="table-line-input" v-if="scope.row.type == 1 && scope.row.consumetype == 1 && !issanke" :ref="makeIndex(scope.$index, 10, orderListRef)" @focus="setIndex(scope.$index, 10, orderListRef)" :value="returnValue(scope, trueOrFalse)" @blur="checkValue($event, scope, trueOrFalse)" size="small" @keyup.enter.native="selectValue($event, scope, trueOrFalse, orderListRef)"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="" label="操作" width="60">
                            <template slot-scope="scope">
                                <el-button type="danger" size="mini" @click="deleterow(scope.$index, orderlist)">删除</el-button>
                            </template>
                        </el-table-column>
                        
                    </el-table>
                </el-form-item>
                <el-form-item label="消费总计">
                    <el-tag size="small" type="success">现金消费</el-tag> +
                    <el-tag size="small">余额消费</el-tag> +
                    <el-tag size="small" type="info">赠送余额</el-tag> +
                    <el-tag size="small" type="danger">卡耗消费</el-tag> = {{fenpeijine.usemoney.toFixed(2)}} + {{fenpeijine.usebalance.toFixed(2)}} + {{fenpeijine.usegiftbalance.toFixed(2)}} + {{fenpeijine.usecard.toFixed(2)}} = {{fenpeijine.zongji.toFixed(2)}}
                </el-form-item>
                <el-form-item label="订单备注">
                    <el-input type="textarea" v-model="order.remarks" placeholder="请输入当前订单描述信息"></el-input>
                </el-form-item>
                <div style="padding: 10px;box-sizing: border-box;height: 60px">      
                    <el-button style="float:right" type="primary" icon="upload2" @click="submitorder(1)" v-qx="quanxian.add">保存并结账</el-button>
                    <el-button style="margin: 0px" type="danger" icon="close" @click="closewin">取消关闭</el-button>
                </div>
            </el-form>
</template>
<script>
import C from '@/common/common.js'
import S from '@/service/shop/search.js'
import P from '@/service/shop/popup.js'
import D from '@/service/common/datas.js'
import keyUpRef from '@/service/shop/keyupref.js'
import Guest from '@/service/shop/guest.js'
import headImg from '#/img/headimg.jpg'
export default {
  name: 'order',
  props: ['orderprops', 'orderlistprops', 'ginfoprops'],
  data () {
    return {
      order: this.orderprops,
      orderlist: this.orderlistprops,
      ginfo: this.ginfoprops,
      userLists: [],
      // 杂项
      guestlist: [], // 选择客户杂项
      loading: true,
      showOwer: true,
      labelPosition: 'top',
      ordermoney: 0,
      issanke: false,
      userlist: [],
      orderListRef: D.openOrder.inputRef,
      orderListRowType: D.openOrder.rowType,
      trueOrFalse: D.trueOrFalse,
      yejiListRef: D.yejiListRef,
      fuwuType: D.fuwuType,
      ginfoid: 1,
      quanxian: {
        add: 'order_add',
        jiezhang: 'order_jie',
        fanjiezhang: 'order_fan',
        dayin: 'order_print',
        fenpei: 'order_fen',
        fanfenpei: 'order_fanfen',
        chongxinfenpei: 'order_chongxin'
      }
    }
  },
  methods: C.assign(keyUpRef, {
    returnValue (scope, data) {
      for (var i = data.length - 1; i >= 0; i--) {
        if (scope.row[scope.column.property] == data[i].value) {
          return data[i].name
        }
      }
      return ''
    },
    blurcheck: function (e, value) {
      e.target.value = value
    },
    checkUserValue (e, typeid) {
      this.fuwuType.forEach(row => {
        if (row.value === typeid) {
          console.log(row.name)
          e.target.value = row.name
        }
      })
    },
    checkUserName (e, item) {
      e.target.value = item.username || ''
    },
    checkValue (e, scope, data) {
      e.target.value = this.returnValue(scope, data)
    },
    selectFuWuType (e, item, data) {
      let v = e.target.value
      if (!item.userid) {
        this.$message.error('请先选择员工！')
        return
      }
      data.forEach((row) => {
        if (row.name == v || row.value == v) {
          e.target.value = row.name
          item.fuwutype = row.value
          item.fuwutypename = row.name
          item.userFenList[0].fuwutype = row.value
          this.orderlist.splice(0, 1, this.orderlist[0])
          this.nextInput(this.orderListRef)
        }
      })
    },
    selectValue (e, scope, data, ref) {
      let v = e.target.value
      let isHave = false
      data.forEach((row) => {
        if (row.name == v || row.value == v) {
          isHave = true
          if (scope.row[scope.column.property] != row.value) {
            scope.row[scope.column.property] = row.value
            // 如果是赠送赋值为零
            if (scope.column.property == 'isgift') {
              this.changeStatus(scope.row)
            }
            // 如果是类别清空当前行数据
            if (scope.column.property == 'rowtype') {
              let data = C.copy(D.openOrderListRow)
              data.rowtype = row.value
              scope.row = Object.assign(scope.row, data)
            }
          }
          e.target.value = row.name
          this.nextInput(ref)
        }
      })
      if (!isHave) {
        C.error('请输入正确的值！')
        e.target.select()
      }
    },
    async searchOpenOrderGoods (e, scope) {
      // 选择客户
      if (!this.ginfo.id || this.ginfo.id == 0) {
        C.error('请先选择客户！')
        return false
      }
      // 判断是否选择行类型
      if (!scope.row.rowtype) {
        C.error('请先选择行类型！')
        return false
      }
      // 开启防重复点击
      if (!C.openLoading()) return false
      let filter = { guestid: this.ginfo.id, keywords: e.target.value, rowtype: scope.row.rowtype }
      let data = await S.searchOpenOrderGoods(filter)
      data = data.data.length == 1
        ? data.data[0]
        : await P.openOrderGoodsPopup(filter, data)
      C.closeLoading()

      if (data && data.id) {
        // console.log(data)
        // 获取
        let consumetype = scope.row.rowtype == 1 || scope.row.rowtype == 2 ? 1 : scope.row.rowtype == 3 ? 2 : 3
        let type = scope.row.rowtype == 1 || scope.row.rowtype == 4 ? 1 : 2
        // console.log(data)
        // 不存在插入，存在进行如下判断
        // 有数据同一行跳转，有数据不同行提示不能重复
        // 判断是否重复（如果rowtype=1或=2产品项目，可通过rowtype和typeid判断）
        // 如果rowtype=3 可以通过rowtype和guestcardinfoid判断
        // 如果rowtype=4 可通过rowtype和tempid判断

        let index, rowdata = {
          type: type,
          typename: data.name,
          consumetype: consumetype,
          price: data.price,
          brandid: data.brandid,
          goodsnum: data.nums
        }
        switch (scope.row.rowtype) {
          case 1:
          case 2:
            index = C.inarray({ rowtype: scope.row.rowtype, typeid: data.id }, this.orderlist)
            rowdata = Object.assign(rowdata, {
              typeid: data.id,
              amount: data.price
            })
            break
          case 3:
            index = C.inarray({ rowtype: scope.row.rowtype, guestcardinfoid: data.id }, this.orderlist)
            // console.log(data)
            let amount = data.cardtype == 1 ? data.xhprice : data.disprice.toFixed(2) - data.amount > 0 ? data.amount : data.disprice.toFixed(2)
            let discount = data.cardtype == 1 ? (amount / data.price).toFixed(2) : data.discount
            rowdata = Object.assign(rowdata, {
              typeid: data.subjectid,
              amount: amount,
              leftAmount: data.amount,
              nownum: data.cardtype == 1 ? '' : data.nownum,
              discount: discount,
              cardtype: data.cardtype,
              cardname: data.cardname,
              guestcardid: data.cardid,
              guestcardinfoid: data.id,
              usecard: data.cardtype == 1 ? 0 : data.disprice.toFixed(2) - data.amount > 0 ? data.amount : data.disprice.toFixed(2)
            })
            break
          case 4:
            index = C.inarray({ rowtype: scope.row.rowtype, tempid: data.id }, this.orderlist)
            rowdata = Object.assign(rowdata, {
              typeid: data.goodsid,
              nownum: data.nownum,
              discount: 0,
              amount: 0,
              brandid: data.brandid,
              tempid: data.id
            })
            break
        }
        rowdata.userTypeList = await S.searchFeatType({
          type: type,
          id: rowdata.typeid
        })

        if (index == -1) {
          scope.row = Object.assign(scope.row, rowdata)
          this.orderlist.splice(0, 1, this.orderlist[0])
          this.nextInput(this.orderListRef)
        } else if (scope.$index == index) {
          this.orderlist.splice(0, 1, this.orderlist[0])
          this.nextInput(this.orderListRef)
        } else {
          C.error('选择数据重复！')
          e.target.select()
          return false
        }
      }
    },
    async firstPopupUser (scope, ind, item) {
      this.setIndex(scope.$index, 11 + ind * 2, this.orderListRef)
      let data = await P.userPopup({ keywords: '', guestid: this.ginfo.id })
      if (data && data.id) {
        // 判断是否重复
        item.userid = data.id
        item.username = data.name
        item.bumenid = data.bumenid
        item.xiaozuid = data.xiaozuid
        item.fuwutype = 0
        item.userFenList = []
        item.userFenList.push({
          id: data.id,
          name: data.name,
          bumenid: data.bumenid,
          xiaozuid: data.xiaozuid,
          worknum: data.worknum,
          disabled: true,
          fuwutype: 0,
          percent: 1
        })
        this.orderlist.splice(0, 1, this.orderlist[0])
        this.nextInput(this.orderListRef)
      }
    },
    selectguest: function (id) {
      this.guestlist.forEach((row) => {
        if (row.id == id) {
          row.headurl = row.headurl != 0 ? row.headurl : headImg
          this.ginfo = Object.assign({}, row)
          this.orderlist = []
          this.addRow(this.orderListRef)
        }
      })
    },
    searchguest: async function (search) {
      let that = this
      if (search != '') {
        this.loading = true
        let data = { pagesize: 30, currentpage: 1, search: search }
        let list = await Guest.getDepartmentGuestList(data)
        that.loading = false
        that.guestlist = list.data
      }
    },
    async searchUser (e, item) {
      // console.log(item)
      if (!C.openLoading()) return false
      let filter = { pagesize: 10, currentpage: 1, keywords: e.target.value, guestid: this.ginfo.id }
      let data = await S.searchUser(filter)
      data = data.list.length == 1
        ? data.list[0]
        : await P.userPopup(filter, data)
      C.closeLoading()
      if (data && data.id) {
        // 判断是否重复
        item.userid = data.id
        item.username = data.name
        item.bumenid = data.bumenid
        item.xiaozuid = data.xiaozuid
        item.fuwutype = 0
        item.userFenList = []
        item.userFenList.push({
          id: data.id,
          name: data.name,
          bumenid: data.bumenid,
          xiaozuid: data.xiaozuid,
          worknum: data.worknum,
          fuwutype: 0,
          disabled: true,
          percent: 1
        })
        this.orderlist.splice(0, 1, this.orderlist[0])
        this.nextInput(this.orderListRef)
      }
    },
    async firstPopupType (scope) {
      this.setIndex(scope.$index, 2, this.orderListRef)
      let data = await P.openOrderGoodsPopup({ guestid: this.ginfo.id, keywords: '', rowtype: scope.row.rowtype })
      if (data && data.id) {
        let consumetype = scope.row.rowtype == 1 || scope.row.rowtype == 2 ? 1 : scope.row.rowtype == 3 ? 2 : 3
        let type = scope.row.rowtype == 1 || scope.row.rowtype == 4 ? 1 : 2
        // console.log(data)
        // 不存在插入，存在进行如下判断
        // 有数据同一行跳转，有数据不同行提示不能重复
        // 判断是否重复（如果rowtype=1或=2产品项目，可通过rowtype和typeid判断）
        // 如果rowtype=3 可以通过rowtype和guestcardinfoid判断
        // 如果rowtype=4 可通过rowtype和tempid判断

        let index, rowdata = {
          type: type,
          typename: data.name,
          consumetype: consumetype,
          price: data.price,
          brandid: data.brandid,
          goodsnum: data.nums
        }
        switch (scope.row.rowtype) {
          case 1:
          case 2:
            index = C.inarray({ rowtype: scope.row.rowtype, typeid: data.id }, this.orderlist)
            rowdata = Object.assign(rowdata, {
              typeid: data.id,
              amount: data.price
            })
            break
          case 3:
            index = C.inarray({ rowtype: scope.row.rowtype, guestcardinfoid: data.id }, this.orderlist)
            let amount = data.cardtype == 1 ? data.xhprice : data.disprice.toFixed(2)
            let discount = data.cardtype == 1 ? (amount / data.price).toFixed(2) : data.discount
            rowdata = Object.assign(rowdata, {
              typeid: data.subjectid,
              amount: amount,
              nownum: data.cardtype == 1 ? '' : data.nownum,
              discount: discount,
              cardtype: data.cardtype,
              cardname: data.cardname,
              guestcardid: data.cardid,
              guestcardinfoid: data.id,
              usecard: data.cardtype == 1 ? 0 : data.disprice.toFixed(2)
            })
            break
          case 4:
            index = C.inarray({ rowtype: scope.row.rowtype, tempid: data.id }, this.orderlist)
            rowdata = Object.assign(rowdata, {
              typeid: data.goodsid,
              nownum: data.nownum,
              discount: 0,
              amount: 0,
              brandid: data.brandid,
              tempid: data.id
            })
            break
        }
        rowdata.userTypeList = await S.searchFeatType({
          type: type,
          id: rowdata.typeid
        })

        if (index == -1) {
          scope.row = Object.assign(scope.row, rowdata)
          this.orderlist.splice(0, 1, this.orderlist[0])
          this.nextInput(this.orderListRef)
        } else if (scope.$index == index) {
          this.orderlist.splice(0, 1, this.orderlist[0])
          this.nextInput(this.orderListRef)
        } else {
          C.error('选择数据重复！')
          // e.target.select()
          return false
        }
      }
    },
    deleterow: C.deleterow,
    closewin: function () {
      C.closeBrowserWindow()
    },
    getTotal: function (row) {
      // 检查数量是否超出（什么时候检查：1，卡耗且为次卡，2，暂存判断数量）
      if (row.consumetype == 2 && row.cardtype == 2 || row.consumetype == 3) {
        if (Number(row.num) > Number(row.nownum)) {
          row.num = row.nownum
          C.error('数量超出可用数量！')
        }
      }
      if (row.consumetype == 2 && row.cardtype == 2) {
        row.usecard = (row.price * row.discount * row.num).toFixed(2) - row.leftAmount > 0 ? row.leftAmount : (row.price * row.discount * row.num).toFixed(2)
        row.amount = row.usecard
      } else {
        row.amount = (row.price * row.discount * row.num).toFixed(2)
      }
      row.isgift = row.amount == 0 ? 1 : 0
    },
    getdiscount: function (row) {
      row.discount = (row.amount / (row.price * row.num)).toFixed(4)
      row.isgift = row.amount == 0 ? 1 : 0
    },
    changeStatus: function (row) {
      row.discount = row.isgift ? 0 : 1
      this.getTotal(row)
    },
    sumorderlist: function (param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (index == 7 || index == 14 || index == 11 || index == 12 || index == 13 || index == 10) {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = sums[index].toFixed(2)
          } else {
            sums[index] = 'N/A'
          }
        }
      })
      return sums
    },
    submitorder: async function (g) {
      if (!this.ginfo.id) {
        C.error('请添加客户！')
        return false
      }
      if (this.orderlist.length <= 0) {
        C.error('请添加产品或项目！')
        return false
      } else {
        for (var i = 0; i < this.orderlist.length; i++) {
          if (this.orderlist[i].goodsnum && this.orderlist[i].num > this.orderlist[i].goodsnum) {
            C.error('选择的产品数量超出了库存数量！')
            return false
          }
          if (this.orderlist[i].userTypeList && this.orderlist[i].userTypeList.length > 0) {
            for (let k = 0; k < this.orderlist[i].userTypeList.length; k++) {
              if (!this.orderlist[i].userTypeList[k].userid) {
                C.error('请填写服务人员!')
                return false
              }
            }
          }
        }
      }
      // 进行匹配
      let usebalance = 0,
        usegiftbalance = 0
      for (let i = 0; i < this.orderlist.length; i++) {
        if (this.orderlist[i].num <= 0 || this.orderlist[i].discount < 0) {
          C.error('第' + (i + 1) + '行数量或者扣填写不正确！')
          return false
        }
        // if (this.orderlist[i].cost > 100) {
        //   C.error('第' + (i + 1) + '行，扣除成本不能超过商品自身价格！')
        //   return false
        // }
        let uamount = C.accAdd(C.accAdd(this.orderlist[i].usemoney, this.orderlist[i].usebalance), this.orderlist[i].usegiftbalance)
        uamount = C.accAdd(this.orderlist[i].usecard, uamount)
        if (C.accSub(this.orderlist[i].amount, uamount) != 0) {
          C.error('第' + (i + 1) + '行金额填写不对称！')
          return false
        }
        // 判断余额或者赠送余额是否足够
        usebalance += Number(this.orderlist[i].usebalance)
        usegiftbalance += Number(this.orderlist[i].usegiftbalance)
      }
      let initConfig = JSON.parse(C.getLocalStorage('initConfig'))
      if (initConfig.isqian) {
        if (usebalance > this.ginfo.balance) {
          if (!confirm('该客户余额已不足，会产生欠款，确定要继续吗？')) {
            return false
          }
        }
      } else {
        if (usebalance > this.ginfo.balance) {
          C.error('客户账户余额不足以支付当前订单！')
          return false
        }
      }

      if (usegiftbalance > this.ginfo.giftbalance) {
        C.error('客户账户赠送余额不足以支付当前订单！')
        return false
      }
      this.order.usegiftbalance = this.fenpeijine.usegiftbalance
      this.order.usebalance = this.fenpeijine.usebalance
      this.order.usemoney = this.fenpeijine.usemoney
      this.order.usecard = this.fenpeijine.usecard
      if (this.issanke) {
        this.ginfo = {
          id: this.ginfoid,
          name: '散客'
        }
      }
      this.order.crossShop = 0
      let shopid = JSON.parse(C.getLocalStorage('initConfig')).shopid
      if (this.ginfo.departmentid != 0 && shopid != this.ginfo.departmentid) {
        this.order.crossShop = 1
      }
      let data = {
        order: this.order,
        ginfo: this.ginfo,
        orderlist: this.orderlist
      }

      /* console.log(data)
      return false */

      let res = await C.ajax('/shop/order/newopenorder', { data: JSON.stringify(data) }, 'post')
      if (res) {
        C.success(res.data.info)
        this.$emit('goto', {
          id: res.data.id,
          status: 0,
          index: 1
        })
      }
    },
    changesanke: function () {
      this.ginfo = {}
      this.orderlist = []
      if (this.issanke) {
        this.ginfo.id = 1
        this.ginfoid = 1
        this.ginfo.name = '散客'
      }
    },
    openGuestPage (id) {
      Guest.openGuestPage(id)
    },
    getrowid (row) {
      return 'rowtype' + row.rowtype + 'type' + row.type + 'typeid' + row.typeid + 'guestcardinfoid' + row.guestcardinfoid
    },
    async selUser (e) {
      let filter = { keywords: e.target.value, guestid: this.ginfo.id }
      let list = await S.searchUser(filter)
      this.userLists = list.list
    },
    selectRow (row, item) {
      item.userFenList = item.userFenList || []
      // 如果存在就不用插入了
      if (item.userFenList.length === 0) {
        item.userFenList.push({
          id: row.id,
          name: row.name,
          bumenid: row.bumenid,
          xiaozuid: row.xiaozuid,
          worknum: row.worknum,
          fuwutype: 0,
          disabled: true,
          percent: 1
        })
        item.userid = row.id
        item.username = row.name
      } else {
        let isHave = false
        item.userFenList.forEach((rows) => {
          if (row.id === rows.id) {
            isHave = true
          }
        })
        if (!isHave) {
          item.userFenList.push({
            id: row.id,
            name: row.name,
            bumenid: row.bumenid,
            xiaozuid: row.xiaozuid,
            worknum: row.worknum,
            fuwutype: 0,
            percent: 0
          })
        }
      }

      this.orderlist.splice(0, 1, this.orderlist[0])
    },
    changePercent (fenList, itmes) {
      let used = 0
      let disabledIndex = 0
      fenList.forEach((row, index) => {
        if (!row.disabled) {
          used += Number(row.percent)
        } else {
          disabledIndex = index
        }
      })
      let left = (1 - used).toFixed(2)
      if (left <= 0) {
        this.$message.error('设置分成比例不正确，或者超出最大值！')
        itmes.percent = 0
        this.orderlist.splice(0, 1, this.orderlist[0])
        return false
      }
      fenList[disabledIndex].percent = left
      this.orderlist.splice(0, 1, this.orderlist[0])
    },
    deleteList (index, item) {
      // 计算分配比例
      this.deleterow(index, item.userFenList)
      this.changePercent(item.userFenList)
    },
    shuaxin () {
      this.orderlist.splice(0, 1, this.orderlist[0])
    }
  }),
  computed: {
    fenpeijine: function () {
      let o = { putong: 0, kahao: 0, zancun: 0, zongji: 0, usemoney: 0, usebalance: 0, usegiftbalance: 0, usecard: 0 }
      this.orderlist.forEach((row) => {
        if (row.consumetype == 1) {
          o.putong += Number(row.amount)
        } else if (row.consumetype == 2) {
          o.kahao += Number(row.amount)
        } else {
          o.zancun += Number(row.amount)
        }
        o.zongji += Number(row.amount)

        o.usemoney += Number(row.usemoney)
        o.usebalance += Number(row.usebalance)
        o.usegiftbalance += Number(row.usegiftbalance)
        o.usecard += Number(row.usecard)
      })
      return o
    },
    expands: function () {
      let list = []
      this.orderlist.forEach((row) => {
        if (row.userTypeList && row.userTypeList.length > 0) {
          list.push('rowtype' + row.rowtype + 'type' + row.type + 'typeid' + row.typeid + 'guestcardinfoid' + row.guestcardinfoid)
        }
      })
      return list
    }
  },
  watch: {
    'order.ginfo.id': async function () {
      let data = await Guest.getGuestInfo(this.order.ginfo.id)
      if (data) this.ginfo = data
    }
  },
  mounted: async function () {
    let filter = { keywords: '', guestid: this.ginfo.id }
    let list = await S.searchUser(filter)
    this.userLists = list.list
  }
}
</script>